<template>
  <section>
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative small-header">
        <el-row>
          <el-col
            :sm="24"
            :md="24"
            :lg="12"
            :xl="12"
            class="flex  align-center justify-start"
          >
            <span class="title-icon margin-right">退货追踪信息</span>
            <el-button
              v-if="returnBatchIndex == 1"
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="downloadCargoInfo"
            >
              导出退货追踪信息
            </el-button>
            <el-button
              v-if="isEdit && returnBatchIndex == 1"
              type="primary"
              size="mini"
              icon="el-icon-upload2"
              @click="uploadDialog = true"
            >
              导入退货追踪信息
            </el-button>
          </el-col>
          <el-col
            :sm="23"
            :md="23"
            :lg="11"
            :xl="11"
            class="flex text-blue align-center justify-between"
          >
            <div>
              <span class="margin-lr">总箱数：{{ totalAmount[0] }} </span>
              <span class="margin-lr">总产品个数：{{ totalAmount[1] }} </span>
              <span class="margin-lr">总签收托盘数：{{ totalAmount[2] }} </span>
              <span class="margin-lr">总签收箱数 ：{{ totalAmount[3] }} </span>
            </div>
            <div>
              <el-button
                v-if="isEdit"
                type="success"
                size="mini"
                @click="enterSelect"
              >
                选择操作
              </el-button>
              <el-button
                v-if="isEdit"
                type="success"
                size="mini"
                @click="batchDel"
              >
                批量删除
              </el-button>
            </div>
          </el-col>
          <el-col
            :sm="1"
            :md="1"
            :lg="1"
            :xl="1"
            class="text-right flex align-center"
            style="justify-content: flex-end;"
          >
            <i
              :class="{
                'el-icon-arrow-down': show,
                'el-icon-arrow-up': !show
              }"
              class="text-lg pointer margin-left"
              @click="show = !show"
            />
          </el-col>
        </el-row>
      </div>
      <div>
        <el-table
          v-show="show"
          ref="multipleTable"
          :header-cell-style="{ background: '#f5f9fc' }"
          size="mini"
          border
          :data="tableData"
          :span-method="objectSpanMethod"
          style="width: 100%;"
          class="margin-top "
          tooltip-effect="light"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <ex-table-column
            v-for="column in tableColumns"
            :key="column.prop"
            :auto-fit="true"
            :fit-header="true"
            :prop="column.prop"
            :label="column.label"
          >
            <template slot-scope="scope" class="column-wrapper">
              <template v-if="column.type === 'boolean'">
                {{
                  scope.row[column.prop] == 0
                    ? '否'
                    : scope.row[column.prop]
                    ? '是'
                    : ''
                }}
              </template>
              <template v-else>
                <!-- <el-input v-model="scope.row[column.prop]" size="mini" /> -->
                {{ scope.row[column.prop] }}
              </template>
            </template>
          </ex-table-column>

          <el-table-column label="操作" width="60" align="center">
            <template slot-scope="scope">
              <i
                class="el-icon-delete padding-lr-sm pointer"
                @click="colDel(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="text-blue margin-top-sm text-center">
        <!-- <span class="margin-right">
          一个追踪号填写一单元格，请勿将多个追踪号混在同一单元格。
        </span> -->
        <span>
          新增或编辑退货跟踪号时，请先导出模板，再导入系统即可，注意不要删掉之前的信息。
        </span>
      </div>
    </el-card>

    <ImportPop
      :upload-dialog.sync="uploadDialog"
      :dialog-title="`导入退货追踪信息`"
      :action-url="`/abroad/waybills/batchUploadReturnTrackData`"
      :file-name="`returnTrackFile`"
      :waybill-id="waybillId"
      @uploadCb="uploadReturnTrackData"
    />
  </section>
</template>

<script>
import ImportPop from '@/components/ImportPop'
import { clone } from '@/utils/clone'
import 'handsontable/languages/zh-CN'
import globalData from '@/utils/config'
import {
  downLoadReturnTrack,
  batchUpdateReturnReceiveGoods,
  batchUpdateReturnTrackOrStockGoods,
  deleteReturnTracking,
  batchDeleteReturnReceive,
  deleteAbroadSku
} from '@/api/abroadWaybill'
import { checkRowsEmpty } from '@/utils/waybill-public'
export default {
  name: 'ReturnInfo',
  components: {
    ImportPop
  },
  props: {
    oldReturnTrackingInfo: {
      type: Array,
      default: function() {
        return [{}]
      }
    },
    returnTrackingInfo: {
      type: Array,
      default: function() {
        return [{}]
      }
    },
    actionUrl: {
      type: String,
      default: ''
    },
    returnBatchIndex: {
      type: Number,
      default: 1
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    waybillId: [String, Number]
  },

  data() {
    return {
      show: false,
      uploadDialog: false,
      autoHeight: 'auto',
      waybillGoodsInfos: [{}, {}, {}, {}, {}],
      multipleSelection: [],
      tableColumns: [
        {
          prop: 'returnNo',
          label: '退货编号'
        },
        {
          prop: 'trackNo', // 指定所指列
          label: '退货追踪号'
        },
        {
          prop: 'shipmentId',
          label: 'Shipment ID'
        },
        {
          prop: 'cartons',
          label: '箱数'
        },
        {
          prop: 'receiptDate',
          label: '仓库签收日期'
        },
        {
          prop: 'receiptPallets',
          label: '签收托盘数'
        },
        {
          prop: 'receiptCartons',
          label: '签收箱数'
        },
        {
          prop: 'sku',
          label: '旧FNSKU'
        },
        {
          prop: 'num',
          label: '产品个数(PCS)'
        },
        {
          prop: 'receiptQuantity',
          label: '签收个数'
        },
        {
          prop: 'location',
          label: 'Location'
        },
        {
          prop: 'boxSpecifications',
          label: 'Size'
        },
        {
          prop: 'receiptCondition',
          label: '签收情况（是否有破损）',
          type: 'boolean'
        }
      ],
      tableData: [],
      spanArr: [],
      pos: 0
    }
  },
  computed: {
    totalAmount() {
      let cartons = 0
      let num = 0
      let receiptPallets = 0
      let receiptCartons = 0
      const arr = []
      for (const i of this.returnTrackingInfo) {
        if (i.trackNo && !arr.includes(i.trackNo)) {
          arr.push(i.trackNo)
          if (i.cartons) {
            cartons += parseInt(i.cartons)
          }
          if (i.receiptPallets) {
            receiptPallets += parseInt(i.receiptPallets)
          }
          if (i.receiptCartons) {
            receiptCartons += parseInt(i.receiptCartons)
          }
        }
        if (i.num) {
          num += parseInt(i.num)
        }
      }

      return [cartons, num, receiptPallets, receiptCartons]
    }
  },
  watch: {
    returnTrackingInfo(newValue, oldValue) {
      // console.log("newValue :>> ", newValue);
      if (newValue.length !== 0) {
        this.tableData = clone(newValue)
        this.getSpanArr(this.tableData)
      }
    }
  },
  mounted() {},
  methods: {
    // 计算表格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if ([0, 1, 2, 3, 4, 5, 6, 7].includes(columnIndex)) {
        // 关键字段  shipmentId 一定要存在
        const target = this.returnTrackingInfo.find(
          x => x.returnNo === row.returnNo
        )
        // console.log('target.spanArr[rowIndex] :>> ', target.spanArr[rowIndex])
        const row_span =
          target && (this.spanArr[rowIndex] || this.spanArr[rowIndex] === 0)
            ? this.spanArr[rowIndex]
            : 1
        return {
          rowspan: row_span,
          colspan: 1
        }
      }
    },
    getSpanArr(arr) {
      // 数据排序，以便合并

      if (arr && arr.length > 0) {
        let spanArr = []
        let pos = 0

        arr.sort((a, b) => parseFloat(a.sortNo) - parseFloat(b.sortNo))
        spanArr = []
        pos = 0
        for (var i = 0; i < arr.length; i++) {
          if (i === 0) {
            spanArr.push(1)
            pos = 0
          } else {
            // 判断当前元素与上一个元素是否相同,因合并第一个所以[0]
            if (arr[i]['trackNo'] === arr[i - 1]['trackNo']) {
              spanArr[pos] += 1
              spanArr.push(0)
            } else {
              spanArr.push(1)
              pos = i
            }
          }
        }
        this.spanArr = spanArr
        // console.log('%cspanArr: ', 'color: #fff; background: #ccc;', spanArr)
        this.pos = pos
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    enterSelect() {
      const ids = []
      for (const s of this.multipleSelection) {
        ids.push(s.id)
      }
      if (ids.length === 0) {
        this.$message.error('请选择已保存过的数据！')
        return
      }

      this.$confirm('是否操作所选退货信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchUpdateReturnTrackOrStockGoods({
          ids,
          waybillId: this.waybillId
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功！')
            this.$emit('getStockInfo')
            this.$emit('getOperation')
          } else {
            this.$message.error(res.message || '操作失败！')
          }
        })
      })
    },
    async batchDel() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要删除的数据')
        return
      }
      const ids = []
      for (const s of this.multipleSelection) {
        ids.push(s.id)
      }

      this.$confirm('删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$store.dispatch('app/toggleDialog', true)

          const res = await batchDeleteReturnReceive({
            ids: ids
          })
          if (res.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          } else {
            this.$message.error(res.message || '操作失败')
          }
          this.$store.dispatch('app/toggleDialog', false)
        })
        .catch(() => {})
    },
    async colDel(row) {
      this.$confirm('删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$store.dispatch('app/toggleDialog', true)

          const res = await deleteAbroadSku({
            id: row.skuId
          })
          if (res.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          } else {
            this.$message.error(res.message || '操作失败')
          }
          this.$store.dispatch('app/toggleDialog', false)
        })
        .catch(() => {})
    },

    closeDialog() {
      this.uploadDialog = false
    },
    async downloadCargoInfo() {
      this.$store.dispatch('app/toggleDialog', true)
      const { fileName } = await downLoadReturnTrack({
        id: this.waybillId
      })
      if (fileName) {
        window.open(globalData.fileUrl + fileName)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    uploadReturnTrackData(file) {
      console.log('uploadCargoInfo', file)
      this.$emit('getReturnInfo')
      this.$emit('getStockInfo')
    }
  }
}
</script>

<style lang="scss" scoped></style>
<style scoped>
/deep/ .el-card__header {
  padding: 8px 20px;
}

.header-save-btn {
  top: 0%;
}
</style>
